import fetch from "node-fetch";

//封装fetch请求
const http = async ({ method, headers, url, params, data }) => {
  //1.处理params，如果有params，需要将其转换成key=value&key=value 的形式，并且需要拼接到url之后
  if (params) {
    //固定写法：new URLSearchParams(obj).toString()
    const str = new URLSearchParams(params).toString();
    url += "?" + str;
  }
  let res;
  //处理data,如果有data，需要发送完整的headers...
  if (data) {
    res = await fetch(url, {
      method: method,
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });
  } else {
    res = await fetch(url);
  }

  //把获取的数据返回出去
  return res.json();
};

//调用http,添加数据
const add = async () => {
  const obj = {
    bookname: "魔法书1",
    author: "wstar",
    publisher: "格兰芬多",
  };
  const res = await http({
    method: "get",
    url: "",
    pa,
  });
  console.log(res);
};
add();
//调用http，查询数据
